//
//  JavascriptSource.m
//  iCodeMac
//
//  Created by Andrew Barry on 14/03/09.
//  Copyright 2009 Barry Computer Services. All rights reserved.
//

#import "JavascriptSource.h"
#import "JavascriptProject.h"
#import "MyTextViewDelegate.h"
#import "SourceTextView.h"

int lineToPos(NSString *str, int line);
extern int lastErrorLine;
extern char *lastErrorMessage;

@implementation JavascriptSource

-(void) awakeFromNib {
	if (savedSource) {
		[textview setString:savedSource];
		[(MyTextViewDelegate *) [textview delegate] codeLoaded];
	}
	[self updateEditEnabled];
}

- (NSString *)windowNibName {
    return @"Editor";
}

- (NSData *)dataOfType:(NSString *)typeName error:(NSError **)outError
{
	NSString *str = [textview string];
    return [str dataUsingEncoding:NSUTF8StringEncoding];
}

- (BOOL)readFromData:(NSData *)data ofType:(NSString *)typeName error:(NSError **)outError
{
	savedSource = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    
    return YES;
}

- (BOOL)writeToURL:(NSURL *)absoluteURL ofType:(NSString *)typeName error:(NSError **)outError {
	[textview saveBreakpoints];
	return [super writeToURL:absoluteURL ofType:typeName error:outError];
}

-(void) saveWindowFrame: (NSWindow *) window {
	NSString *docFile = [self documentFile];
	
	JavascriptProject *project = [JavascriptProject projectForDocument: self];
	if (project) {
		[project saveFrame:[window frame] forWindow: docFile];
	}
}

-(void)windowDidMove:(NSNotification *)notification {
	[self saveWindowFrame: [notification object]];
}

-(void)windowDidResize:(NSNotification *)notification {
	[self saveWindowFrame: [notification object]];
}

- (void)windowWillClose:(NSNotification *)notification {
	NSWindow *wnd = [notification object];
	if (![wnd isDocumentEdited]) {
		[textview saveBreakpoints];
	}
}

-(NSString *) documentFile {
	NSURL *docURL = [self fileURL];
	if (!docURL)
		return nil;
	
	if (![docURL isFileURL])
		return nil;
	NSString *docPath = [docURL path];
	return [docPath lastPathComponent];
}

-(void)makeWindowControllers {
	NSWindowController *ctl = [[NSWindowController alloc] initWithWindowNibName:@"Editor" owner:self];
	[self addWindowController:ctl];
	
	NSWindow *window = [[[self windowControllers] objectAtIndex:0] window];
	NSString *docFile = [self documentFile];
	NSRect f;
	JavascriptProject *project = [JavascriptProject projectForDocument: self];
	if (docFile != nil && [project savedFrame: &f forWindow:docFile]) {
		[window setFrame: f display:YES];
	}
}

-(void) errorSheetClose:(NSAlert *)alert returnCode:(int)returnCode contextInfo:(void *)contextInfo {
}

-(void) showError: (NSString *) message atLine: (int) lineno forScript: (NSString *) filename {
	NSWindow *window = [[[self windowControllers] objectAtIndex:0] window];

	if (lineno) {
		int pos = lineToPos([textview string], lineno);
		[textview setSelectedRange:NSMakeRange(pos, 0)];
		[textview scrollRangeToVisible:NSMakeRange(pos, 0)];
		[textview setRunMarker:lineno];
	}

	if (message) {
		NSAlert *alert = [[NSAlert alloc] init];
		[alert setMessageText:lineno ? [NSString stringWithFormat:@"Error at line %d", lineno] : @"Error"];
		[alert setInformativeText:message];
		[alert addButtonWithTitle:@"Close"];
		[alert setAlertStyle:NSWarningAlertStyle];
		
		[alert beginSheetModalForWindow:window modalDelegate:self didEndSelector:@selector(errorSheetClose:returnCode:contextInfo:) contextInfo:nil];
	}
}

-(void) updateEditEnabled {
	JavascriptProject *project = [JavascriptProject projectForDocument: self];
	[textview setEditable:project == nil || ![project isDebugging]];
}

-(void) clearStop {
	[textview setRunMarker:0];
}

-(void) setRunMaker:(int) line {
	[textview setRunMarker:line];
}

-(void) saveBreakpoints {
	[textview saveBreakpoints];
}

+(bool)precompileSource: (NSString *) path {
	/*
	NSString *script = [NSString stringWithContentsOfFile: path encoding: NSUTF8StringEncoding error: nil];
	if (!script)
		return true;
	const char *strScript = [script UTF8String];
	if (!JS_CompileScript(cx, global, strScript, strlen(strScript), "source", 1)) {
		NSURL *docURL = [NSURL fileURLWithPath:path];
		JavascriptSource *sourceDoc = [[NSDocumentController sharedDocumentController] openDocumentWithContentsOfURL:docURL display:YES error: nil];
		[sourceDoc showError:[NSString stringWithCString:lastErrorMessage] atLine:lastErrorLine forScript:path];
		return false;
	}
	*/
	return true;
}

@end
